//! # 插件系统实现
//! 
//! 本模块提供了RustCloud框架的内置插件实现。

use crate::advanced_builder::traits::*;
use crate::advanced_builder::AdvancedRustCloudBuilder;
use rustcloud_core::{ServiceResult, ServiceError};
use std::collections::HashMap;

/// 内置插件
pub struct DatabasePlugin {
    connection_string: String,
}

impl DatabasePlugin {
    pub fn new(connection_string: String) -> Self {
        Self { connection_string }
    }
}

#[async_trait::async_trait]
impl BuilderPlugin for DatabasePlugin {
    fn name(&self) -> &str {
        "database"
    }

    fn description(&self) -> &str {
        "数据库连接插件"
    }

    async fn apply(&self, builder: &mut AdvancedRustCloudBuilder) -> ServiceResult<()> {
        // 配置数据库相关设置
        builder.config.service.tags.insert(
            "database.connection".to_string(),
            self.connection_string.clone(),
        );
        
        tracing::info!("数据库插件配置完成");
        Ok(())
    }
}

/// Redis缓存插件
pub struct RedisPlugin {
    redis_url: String,
}

impl RedisPlugin {
    pub fn new(redis_url: String) -> Self {
        Self { redis_url }
    }
}

#[async_trait::async_trait]
impl BuilderPlugin for RedisPlugin {
    fn name(&self) -> &str {
        "redis"
    }

    fn description(&self) -> &str {
        "Redis缓存插件"
    }

    async fn apply(&self, builder: &mut AdvancedRustCloudBuilder) -> ServiceResult<()> {
        // 启用缓存配置
        builder.config.components.proxy.cache.enabled = true;
        builder.config.service.tags.insert(
            "cache.redis.url".to_string(),
            self.redis_url.clone(),
        );
        
        tracing::info!("Redis插件配置完成");
        Ok(())
    }
}

/// HTTP客户端插件
pub struct HttpClientPlugin {
    base_url: String,
    timeout_seconds: u64,
}

impl HttpClientPlugin {
    pub fn new(base_url: String, timeout_seconds: u64) -> Self {
        Self { base_url, timeout_seconds }
    }
}

#[async_trait::async_trait]
impl BuilderPlugin for HttpClientPlugin {
    fn name(&self) -> &str {
        "http_client"
    }

    fn description(&self) -> &str {
        "HTTP客户端插件"
    }

    fn priority(&self) -> i32 {
        10 // 较高优先级
    }

    async fn apply(&self, builder: &mut AdvancedRustCloudBuilder) -> ServiceResult<()> {
        // 配置HTTP客户端相关设置
        builder.config.service.tags.insert(
            "http.client.base_url".to_string(),
            self.base_url.clone(),
        );
        builder.config.service.tags.insert(
            "http.client.timeout_seconds".to_string(),
            self.timeout_seconds.to_string(),
        );
        
        tracing::info!("HTTP客户端插件配置完成");
        Ok(())
    }
}

/// 安全插件
pub struct SecurityPlugin {
    jwt_secret: String,
    enable_auth: bool,
}

impl SecurityPlugin {
    pub fn new(jwt_secret: String, enable_auth: bool) -> Self {
        Self { jwt_secret, enable_auth }
    }
}

#[async_trait::async_trait]
impl BuilderPlugin for SecurityPlugin {
    fn name(&self) -> &str {
        "security"
    }

    fn description(&self) -> &str {
        "安全插件"
    }

    fn dependencies(&self) -> Vec<String> {
        vec!["http_client".to_string()] // 依赖HTTP客户端插件
    }

    async fn apply(&self, builder: &mut AdvancedRustCloudBuilder) -> ServiceResult<()> {
        // 配置安全相关设置
        if self.enable_auth {
            builder.config.components.gateway = Some(crate::config::GatewayConfig {
                enabled: true,
                port: 8080,
                routes: Vec::new(),
                middleware: crate::config::MiddlewareConfig {
                    auth: Some(crate::config::AuthMiddlewareConfig {
                        auth_type: "jwt".to_string(),
                        jwt: Some(crate::config::JwtConfig {
                            secret: self.jwt_secret.clone(),
                            expiration_seconds: 3600,
                        }),
                    }),
                    rate_limit: None,
                    cors: None,
                },
            });
        }
        
        tracing::info!("安全插件配置完成");
        Ok(())
    }
}